package mobile

import (

	// "sword"

	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"math"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"tcsc/models"
	"tcsc/sword"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/gorilla/websocket"
)

var P_e = `解析form失败:`
var U_e = `更新失败:`
var I_e = `插入失败:`
var Tparse = `2006-01-02 15:04:05`

type BaseController struct {
	beego.Controller
	Uid       string
	Share_Uid string
	ShopId    string
	ShopIdAll string //逗号分隔服务中心的所有id
}

func (c *BaseController) Prepare() {
	// user_agent := c.Ctx.Request.Header.Get("User-Agent")
	// iswx := strings.Index(user_agent, "MicroMessenger")
	// beego.Debug(user_agent)
	// beego.Debug(iswx)
	// beego.Debug(c.Ctx.Request.Header.Get("Accept"))
	// c.SetSession("wechat", "108")
	sess := c.GetSession("wechat")
	// city := c.GetString("city")
	// beego.Debug("===============sess", sess)
	// beego.Debug("===============shopid", c.ShopId)
	// beego.Debug("===============", c.GetSession("shopId"))

	if c.GetSession("shopId") == nil {
	} else {
		// c.ShopId = ""
		c.ShopId = c.GetSession("shopId").(string)
	}
	if c.ShopIdAll == "" {
		var idArr []string
		shopid := models.Query(`select id from mt_shop where style=1`)
		for _, v := range shopid {
			idArr = append(idArr, v["id"].(string))
		}
		c.ShopIdAll = strings.Join(idArr, ",")
	}
	c.Data["currentcity"] = c.GetSession("city")
	appCity := c.Ctx.Request.Header.Get("city")
	if appCity != "" {
		s := "city=" + appCity
		m, _ := url.ParseQuery(s)
		appCity = m["city"][0]
		if c.ShopId == "" && appCity != "台州市" {
			if area := models.Query(`select code from mt_area where name=?`, appCity); area != nil {
				if shop := models.Query(`select id from mt_shop where style=1 and status=1 and censoring=1 and city=?`, area[0]["code"]); shop != nil {
					c.SetSession("shopId", shop[0]["id"].(string))
					c.ShopId = shop[0]["id"].(string)
				}
			}
		}
	}

	if sess != nil {
		// if city != "" && city != "台州市" {
		// 	if code := models.Query(`select code from mt_area where name = '` + city + `'`); code != nil {
		// 		if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ` + code[0]["code"].(string)); shop != nil {
		// 			c.SetSession("shopId", shop[0]["id"].(string))
		// 			c.ShopId = shop[0]["id"].(string)
		// 			beego.Debug("-----------------shopid", c.ShopId)
		// 			// c.ShopId = ""
		// 		}
		// 	}
		// }
		// if vipGid := models.Query(`select a.gid from mt_member_vip a left join mt_member_vip_order b on b.uid=? where a.id=b.vid`, sess); vipGid != nil {
		// 	if vipGid[0]["gid"].(string) != "0" {
		// 		c.ShopId = vipGid[0]["gid"].(string)
		// 	}
		// }
		c.Uid = sess.(string)
	} else if c.Ctx.Request.Header.Get("uid") != "" {
		// if vipGid := models.Query(`select a.gid from mt_member_vip a left join mt_member_vip_order b on b.uid=? where a.id=b.vid`, sess); vipGid != nil {
		// 	if vipGid[0]["gid"].(string) != "0" {
		// 		c.ShopId = vipGid[0]["gid"].(string)
		// 	}
		// }
		c.Uid = c.Ctx.Request.Header.Get("uid")
		// if c.GetSession("shopId") == nil {
		// 	city := ""
		// 	city = c.Ctx.Request.Header.Get("city")
		// 	if city != "" {
		// 		s := "city=" + city
		// 		m, _ := url.ParseQuery(s)
		// 		city = m["city"][0]
		// 		if city == "'台州市'" {
		// 			city = ""
		// 		}
		// 	}
		// 	if c.Uid != "" && c.ShopId == "" && city != "" {
		// 		if code := models.Query(`select code from mt_area where name = '` + city + `'`); code != nil {
		// 			if shop := models.Query(`select id from mt_shop where style = 1 and status = 1 and censoring = 1 and city = ` + code[0]["code"].(string)); shop != nil {
		// 				c.SetSession("shopId", shop[0]["id"].(string))
		// 				c.ShopId = shop[0]["id"].(string)
		// 				// c.ShopId = ""
		// 			}
		// 		}
		// 	} else {
		// 		c.ShopId = ""
		// 	}
		// } else {
		// 	c.ShopId = c.GetSession("shopId").(string)
		// }
	}
	c.Data["coor"] = c.GetSession("coor")
	if c.GetString("share_uid") != "" {
		c.SetSession("share_uid", c.GetString("share_uid"))
	}
	url := c.Ctx.Request.RequestURI
	uri2 := strings.Split(url, "/")[2]
	sesslogin := c.GetSession("login")
	if sesslogin == nil && c.Uid == "" && !c.IsAjax() {
		user_agent := c.Ctx.Request.Header.Get("User-Agent")
		iswx := strings.Index(user_agent, "MicroMessenger")
		if iswx != -1 {
			// c.SetSession("url", url)
			c.Ctx.Redirect(302, "/mobile/login_wechat_check?url="+url)
		}
	}
	if uri2 == "my" || uri2 == "del" || uri2 == "shopcar" {
		if c.Uid == "" {
			if c.IsAjax() {
				c.Data["json"] = 962 //未登入
				defer c.ServeJSON()
				return
			} else {
				c.Ctx.Redirect(302, "/mobile/login?url="+url)
			}
		}
	}
	if prohibit := models.Query(`select id from mt_member where prohibit=1 and id=?`, c.Uid); prohibit != nil {
		c.Data["json"] = ""
		c.ServeJSON()
		return
	}
	c.Data["share_uid"] = c.Uid
	c.Data["share"] = models.GetAccessToken(url)
	// utils.Display("share", c.Data["share"])
	c.Data["system"] = models.System
}

type Del struct {
	BaseController
}

func (c *Del) Get() {
	defer c.ServeJSON()
	table := c.GetString("table")
	id := c.GetString("id")
	if istrue := models.Query(`select id from ` + table + ` where id=` + id + ` and uid=` + c.Uid); istrue != nil {
		if err := models.Exec(`update ` + table + ` set status=0 where id=` + id); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			c.Data["json"] = 1
		}
	} else {
		c.Data["json"] = 0
	}
}

type Coor struct {
	BaseController
}

func (c *Coor) Get() {
	c.EnableRender = false
	latitude := c.GetString("latitude")
	longitude := c.GetString("longitude")
	if c.Uid != "" {
		if err := models.Query(`update mt_member set latitude='` + latitude + `',longitude='` + longitude + `' where id=` + c.Uid); err != nil {
			beego.Debug(err)
		} else {
			c.SetSession("coor", latitude+","+longitude)
		}
	}
}

type Hub struct {
	// Registered clients.
	clients map[*Client]bool

	// Inbound messages from the clients.
	broadcast chan []byte

	// Register requests from the clients.
	register chan *Client

	// Unregister requests from clients.
	unregister chan *Client
}

func newHub() *Hub {
	return &Hub{
		broadcast:  make(chan []byte),
		register:   make(chan *Client),
		unregister: make(chan *Client),
		clients:    make(map[*Client]bool),
	}
}

func (h *Hub) run() {
	for {
		select {
		case client := <-h.register:
			h.clients[client] = true
		case client := <-h.unregister:
			if _, ok := h.clients[client]; ok {
				delete(h.clients, client)
				close(client.send)
			}
		case message := <-h.broadcast:
			//获取聊天双方的id之和与id之积
			//id 之和与id之积唯一
			var sum string
			var mult string
			var sid string
			var uid string
			for client := range h.clients {
				if client.Isread == 1 {
					beego.Debug(client)
					sid = client.Sid
					sms := models.Query(`select fid,uid from mt_sms where id=` + sid + ` limit 1`)[0]
					a := fmt.Sprint(sms["fid"])
					b := fmt.Sprint(sms["uid"])
					uid = b
					beego.Debug(uid)
					beego.Debug(b)
					beego.Debug(a)
					mult = sword.Mult(a, b)
					sum = sword.Sum(a, b)
					break
				}
			}
			var iscoon = false
			for client := range h.clients {
				if client.Type == 0 {
					//移动端 设置sid 一对一聊天
					if sum == client.Sum && mult == client.Mult {
						client.Sid = sid
						if client.Uid == uid {
							iscoon = true
						}
						select {
						case client.send <- message:
						default:
							close(client.send)
							delete(h.clients, client)
						}
					}
				} else {
					//pc端 查看是否与自己有关
					sms := models.Query(`select fid,uid from mt_sms where id=` + sid + ` limit 1`)[0]
					a := fmt.Sprint(sms["fid"])
					b := fmt.Sprint(sms["uid"])
					if a == client.Uid || b == client.Uid {
						client.Sid = sid
						if client.Uid == uid {
							iscoon = true
						}
						select {
						case client.send <- message:
						default:
							close(client.send)
							delete(h.clients, client)
						}
					}
				}
			}
			for client := range h.clients {
				if client.Isread == 1 {
					client.Iscoon = iscoon
					break
				}
			}
		}
	}
}

const (
	// Time allowed to write a message to the peer.
	writeWait = 10 * time.Second

	// Time allowed to read the next pong message from the peer.
	pongWait = 60 * time.Second

	// Send pings to peer with this period. Must be less than pongWait.
	pingPeriod = (pongWait * 9) / 10

	// Maximum message size allowed from peer.
	maxMessageSize = 512
)

var (
	newline = []byte{'\n'}
	space   = []byte{' '}
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

type Client struct {
	hub *Hub

	// The websocket connection.
	conn *websocket.Conn

	// Buffered channel of outbound messages.
	send chan []byte

	Sum string //id之和

	Mult string //id之积

	Sid string //sms id

	Uid string //链接用户id

	Isread int //是否为发送用户

	Iscoon bool //是否连接

	Type int //类型 0:客户端  1服务端客服
}

type Message struct {
	Uid     string `json:"uid"`
	Fid     string `json:"fid"`
	Message string `json:"message"`
}

// reads from this goroutine.
func (c *Client) readPump() {
	defer func() {
		c.hub.unregister <- c
		c.conn.Close()
	}()
	c.conn.SetReadLimit(maxMessageSize)
	c.conn.SetReadDeadline(time.Now().Add(pongWait))
	c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		var mess Message
		err := c.conn.ReadJSON(&mess)
		if err != nil {
			beego.Debug(err)

			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Printf("error: %v", err)
			}
			break
		}
		res, err := models.Orm().Raw(fmt.Sprintf(`insert into mt_sms (uid,fid,content,addtime) values (%v,%v,'%v','%v')`, mess.Uid, mess.Fid, mess.Message, sword.Gettimes(""))).Exec()
		if err != nil {
			beego.Debug(err)
			break
		}
		sid, _ := res.LastInsertId()
		c.Sid = fmt.Sprint(sid)
		c.Isread = 1
		message, err := json.Marshal(mess)
		if err != nil {
			beego.Debug(err)
			break
		}
		message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
		c.hub.broadcast <- message
	}
}

// writePump pumps messages from the hub to the websocket connection.
//
// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func (c *Client) writePump() {
	ticker := time.NewTicker(pingPeriod)
	defer func() {
		ticker.Stop()
		c.conn.Close()
	}()
	for {
		select {
		case message, ok := <-c.send:
			c.conn.SetWriteDeadline(time.Now().Add(writeWait))
			if !ok {
				// The hub closed the channel.
				c.conn.WriteMessage(websocket.CloseMessage, []byte{})
				return
			}
			w, err := c.conn.NextWriter(websocket.TextMessage)
			if err != nil {
				return
			}
			w.Write(message)

			// Add queued chat messages to the current websocket message.
			n := len(c.send)
			for i := 0; i < n; i++ {
				w.Write(newline)
				w.Write(<-c.send)
			}

			if err := w.Close(); err != nil {
				return
			}
			//pc端
			// if c.Type == 1 {

			uid := c.Uid
			sid := c.Sid
			//如果被发送的信息可以查询到  更新状态 不然 发推送
			if c.Isread == 1 {
				if isc := models.Query(`select id from mt_sms where id=` + sid + ` and fid=` + uid + ` limit 1`); isc != nil {
					if c.Iscoon {
						models.Exec(`update mt_sms set state=1 where id=` + sid)

					} else {
						mess := models.Query(`select a.fid,b.wx_openid_gzh,c.monicker,a.content from mt_sms a left join mt_member b on a.uid=b.id 
					left join mt_member c on a.fid=c.id where a.id=` + sid + ` limit 1`)[0]
						data2 := map[string]map[string]interface{}{
							"first":    {"value": `您收到一条新消息`},
							"keyword1": {"value": mess["monicker"]},
							"keyword2": {"value": mess["content"], "color": "#e4393c"},
							"keyword3": {"value": `尽快处理`, "color": "#9c9c9c"},
							"remark":   {"value": `亲要及时回复哟~`},
						}
						models.Push(fmt.Sprint(mess["wx_openid_gzh"]), `xp7KhQVtAezh_rxPdnxE9bpzflPJv1xqSaDKlBhiE9Y`, data2, models.Urlc+"/mobile/my/message_content?id="+mess["fid"].(string), "")
					}
				}
			}
			c.Isread = 0
			// }
		case <-ticker.C:
			c.conn.SetWriteDeadline(time.Now().Add(writeWait))
			if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}

type Ws struct {
	BaseController
}

// type Clients struct {
// 	Conn *websocket.Conn
// 	Uid  string
// 	Fid  string
// }

var Hubn = newHub()

func (c *Ws) Get() {
	go Hubn.run()
	c.EnableRender = false
	conn, err := upgrader.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil)
	if err != nil {
		beego.Debug(err)
	} else {
		id := c.GetString("id")
		uid := c.Uid
		t := c.GetString("type")

		if t == "" {
			if id == "" || uid == "" {
				conn.Close()
			} else {
				client := &Client{hub: Hubn, conn: conn, send: make(chan []byte, 256), Sum: sword.Sum(uid, id), Mult: sword.Mult(uid, id), Isread: 0, Sid: "0", Uid: uid, Type: 0, Iscoon: false}
				client.hub.register <- client
				go client.writePump()
				go client.readPump()
			}
		} else if t == "admin" {
			se := c.GetSession("pc")
			if se == nil {
				return
			}
			uid = se.(string)
			client := &Client{hub: Hubn, conn: conn, send: make(chan []byte, 256), Sum: "0", Mult: "0", Isread: 0, Sid: "0", Uid: uid, Type: 1, Iscoon: false}
			client.hub.register <- client
			go client.writePump()
			go client.readPump()
		} else if t == "app" {
			uid = c.GetString("uid")
			client := &Client{hub: Hubn, conn: conn, send: make(chan []byte, 256), Sum: sword.Sum(uid, id), Mult: sword.Mult(uid, id), Isread: 0, Sid: "0", Uid: uid, Type: 0, Iscoon: false}
			client.hub.register <- client
			go client.writePump()
			go client.readPump()
		}
	}
}
func PayPush(oids string) {
	nowtimes := sword.Gettimes("")
	order := models.Query(`select a.gid,a.paytype,a.ordernum,a.money,a.addtime,a.carid,b.wx_openid_gzh,b.monicker from mt_order a 
		left join mt_member b on a.uid=b.id where a.id in(` + oids + `)`)
	for _, v := range order {
		caridArr := strings.Split(v["carid"].(string), ",")
		for _, vt := range caridArr {
			orderCar := models.Query(`select pid from mt_order_car where id=` + vt)
			if orderCar != nil {
				sellnum := models.Query(`select sellnum from mt_product where id=` + orderCar[0]["pid"].(string))[0]["sellnum"].(string)
				if err := models.Query(`update mt_product set sellnum=sellnum+` + sellnum + ` where id=` + orderCar[0]["pid"].(string)); err != nil {
					beego.Debug(err)
				}
			}

		}
		var paytype string
		switch v["paytype"].(string) {
		case "1":
			paytype = `余额支付`
		case "2":
			paytype = `微信支付`
		case "3":
			paytype = `支付宝支付`
		}
		gid := fmt.Sprint(v["gid"])
		var g orm.Params
		uopenid := fmt.Sprint(v["wx_openid_gzh"])
		if gid == "0" {
			g = models.Query(`select a.name,b.wx_openid_gzh as openid from mt_systems a left join mt_member b on a.uid=b.id`)[0]
			g["openid"] = `ozAyh0hReTtr069DAFrxxdqwpCpk`
		} else {
			g = models.Query(`select a.name,b.wx_openid_gzh as openid from mt_shop a left join mt_member b on a.uid=b.id where a.id=` + gid)[0]
		}
		gopenid := fmt.Sprint(g["openid"])
		gname := fmt.Sprint(g["name"])
		data := map[string]map[string]interface{}{
			"first":    {"value": `您已支付成功~`},
			"keyword1": {"value": v["ordernum"], "color": `#36353A`},
			"keyword2": {"value": v["money"], "color": `#e31939`},
			"keyword3": {"value": gname, "color": "#36353A"},
			"keyword4": {"value": v["monicker"], "color": `#36353A`},
			"keyword5": {"value": paytype},
			"remark":   {"value": `请等待卖家发货~`},
		}
		models.Push(uopenid, `lX1m4MHH0nBLnQk4teo1ATj_lwLBKoruL_ZiSTLYkhQ`, data, models.Urlc+"/mobile/my/order", "")
		data2 := map[string]map[string]interface{}{
			"first":    {"value": `客户已经完成支付`},
			"keyword1": {"value": v["ordernum"], "color": `#36353A`},
			"keyword2": {"value": v["money"], "color": `#e31939`},
			"keyword3": {"value": gname, "color": "#36353A"},
			"keyword4": {"value": v["monicker"], "color": `#36353A`},
			"keyword5": {"value": paytype},
			"remark":   {"value": `对方已经完成支付,请尽快发货~`},
		}
		if gid == "0" {
			//arr := []string{`ozAyh0hReTtr069DAFrxxdqwpCpk`, `ozAyh0t31zHP9-ueakhHrwpqUfVE`, `ozAyh0vTHc_9wwg4VQVqR-IFJ0t8`, `ozAyh0h9w6u5hPZBXuA-T2WVA_TM`}
			arr := []string{`ozAyh0t31zHP9-ueakhHrwpqUfVE`, `ozAyh0gWWiiuHU3ClLMXvGomfF3U`, `ozAyh0mzgxR8Dk2Mo9fwLLzt0244`}
			for _, v := range arr {
				models.Push(v, `lX1m4MHH0nBLnQk4teo1ATj_lwLBKoruL_ZiSTLYkhQ`, data2, models.Urlc+"/mobile/my/order_manage", "")
			}
		} else {
			models.Push(gopenid, `lX1m4MHH0nBLnQk4teo1ATj_lwLBKoruL_ZiSTLYkhQ`, data2, models.Urlc+"/mobile/my/order_manage", "")
		}
		if gid == "0" {
			carid := fmt.Sprint(v["carid"])
			shop := models.Query(`select c.id,c.bid from mt_order_car a left join mt_product b on a.pid=b.id left join mt_shop c on c.bid=b.bid where a.id in(` + carid + `) group by b.bid`)
			for _, vt := range shop {
				gids := fmt.Sprint(vt["id"])
				bids := fmt.Sprint(vt["bid"])
				s := models.Query(`select a.name,b.wx_openid_gzh from mt_shop a left join mt_member b on a.uid=b.id where a.id=` + gids)[0]
				sopenid := fmt.Sprint(s["wx_openid_gzh"])
				pr := models.Query(`select b.title,a.num from mt_order_car a join (select * from mt_product where bid=` + bids + `) b
				on a.pid=b.id where a.id in(` + carid + `)`)
				var pname []string
				for _, p := range pr {
					pname = append(pname, fmt.Sprintf(`%v X %v`, p["title"], p["num"]))
				}
				// driver := models.Query(`
				// 	select wx_openid_gzh,concat(',',driverarea,',') as driverarea
				// 	from mt_member
				// 	where driver=1 and driverarea like '%,` + fmt.Sprint(v["area"]) + `,%'`)
				// if driver != nil {
				// 	data3 := map[string]map[string]interface{}{
				// 		"first":    {"value": `您有一个新的订单需要提货`},
				// 		"keyword1": {"value": v["ordernum"], "color": `#36353A`},
				// 		"keyword2": {"value": strings.Join(pname, "、"), "color": `#e31939`},
				// 		"keyword3": {"value": nowtimes, "color": "#9c9c9c"},
				// 		"remark":   {"value": `请您尽快前往提货`},
				// 	}
				// 	models.Push(fmt.Sprint(driver[0]["wx_openid_gzh"]), `cXLsiC-KrPaiYpOzNf4ZWa1ERzUt6v9uNhB-ur1IZso`, data3, models.Urlc+"/mobile/my/shop", "")
				// }
				data3 := map[string]map[string]interface{}{
					"first":    {"value": `您有一个新的订单需要备货`},
					"keyword1": {"value": v["ordernum"], "color": `#36353A`},
					"keyword2": {"value": strings.Join(pname, "、"), "color": `#e31939`},
					"keyword3": {"value": nowtimes, "color": "#9c9c9c"},
					"remark":   {"value": `请您尽快处理`},
				}
				models.Push(sopenid, `cXLsiC-KrPaiYpOzNf4ZWa1ERzUt6v9uNhB-ur1IZso`, data3, models.Urlc+"/mobile/my/shop", "")
			}
		}
	}
}
func ProductList(sql, uid string) []orm.Params {
	info := models.Query(sql)
	nowtimes := sword.Gettimes("")
	o := models.Orm()
	wg := sync.WaitGroup{}
	for _, vv := range info {
		wg.Add(1)
		go func(v orm.Params) {
			defer wg.Done()
			id := v["id"].(string)
			v["active"] = 0
			var sales []orm.Params
			o.Raw(`select price from mt_active_sales where pid=` + id + ` and status=1 and end=0 and 
			starttime<='` + nowtimes + `' and endtime>='` + nowtimes + `'`).Values(&sales)
			if sales != nil {
				v["price"] = sales[0]["price"]
				v["active"] = 2
			}
			if fmt.Sprint(v["isvip"]) == "1" {
				if uid != "" {
					var gid string
					var g []orm.Params
					o.Raw(`select b.id,b.style 
								from mt_product a 
								left join mt_shop b on a.gid=b.id 
								where a.id=?`, id).Values(&g)
					if g == nil || fmt.Sprint(g[0]["style"]) == "0" || g[0]["id"] == nil {
						gid = "0"
					} else {
						gid = fmt.Sprint(g[0]["id"])
					}
					var mem []orm.Params
					o.Raw(`
					select b.fold 
					from mt_member_vip_order a 
					join (select * from mt_member_vip where gid=? and status=1) b on a.vid=b.id 
					where a.uid=?`, gid, uid).Values(&mem)
					if mem != nil {
						if fold := fmt.Sprint(mem[0]["fold"]); fold != "" && fold != "<nil>" {
							v["price"] = sword.Divi(sword.Mult(fmt.Sprint(v["price"]), fold), "100")

						}
					}
				}
			}
			var gbuy []orm.Params

			o.Raw(`select price from mt_active_gbuy where pid=` + id + ` and end=0 and 
			starttime<='` + nowtimes + `' and endtime>='` + nowtimes + `'`).Values(&gbuy)
			if gbuy != nil {
				v["price"] = gbuy[0]["price"]
				v["active"] = 1
			}

			var goods []orm.Params
			var nogoods []orm.Params
			var sellnum []orm.Params
			o.Raw(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + v["id"].(string) + `) b 
			on a.cid=b.id where a.score>=3`).Values(&goods)
			good := goods[0]["num"].(string)
			o.Raw(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + v["id"].(string) + `) b 
			on a.cid=b.id where a.score<3`).Values(&nogoods)
			nogood := nogoods[0]["num"].(string)
			if nogood == "0" {
				v["hp"] = "100"
			} else {
				goodi, _ := strconv.Atoi(good)
				nogoodi, _ := strconv.Atoi(nogood)
				v["hp"] = goodi / (goodi + nogoodi)
			}
			keywords := fmt.Sprint(v["keywords"])
			if keywords != "" {
				v["keywords"] = strings.Split(keywords, " ")
			} else {
				var keyword []string
				v["keywords"] = keyword
			}
			if fmt.Sprint(v["issellnum"]) == "1" {
				o.Raw(`select sum(a.num) as num from mt_order_car a where a.status>1 and a.pid=` + v["id"].(string)).Values(&sellnum)
				if sellnums, ok := sellnum[0]["num"].(string); ok {
					v["sellnum"] = sellnums
				} else {
					v["sellnum"] = "0"
				}
			}
		}(vv)
	}
	wg.Wait()
	return info
}

func OrderConfirmF(oid string) error {
	nowtimes := sword.Gettimes("")
	system := models.Systems()
	orders := models.Query(`select a.id,a.gid,a.money,a.ordernum,a.uid,b.uid as puid,a.addtime,a.type,a.carid,a.shippingtime 
	 from mt_order a left join mt_member b on a.uid=b.id where a.id=` + oid)
	for _, order := range orders {
		id := fmt.Sprint(order["id"])
		carid := fmt.Sprint(order["carid"])
		money := fmt.Sprint(order["money"])
		uid := fmt.Sprint(order["uid"])
		puid := fmt.Sprint(order["puid"])
		ot := fmt.Sprint(order["type"])
		gid := fmt.Sprint(order["gid"])
		o := models.Orm()
		o.Begin()
		if _, err := o.Raw(`update mt_order set status=4,goodtime='` + sword.Gettimes("") + `' where id=` + id).Exec(); err != nil {
			beego.Debug(err)
			o.Rollback()
			return err
		}
		var mem orm.Params
		if mems := models.Query(`
			select a.type,b.fold,a.wx_openid_gzh,a.distribution 
			from mt_member a 
			left join mt_member_vip_order c on a.id=c.uid 
			left join mt_member_vip b on b.id=c.vid 
			where a.id=` + puid); mems != nil {
			mem = mems[0]
		}
		umem := models.Query(`
			select b.fold,a.wx_openid_gzh 
			from mt_member a 
			left join mt_member_vip_order c on a.id=c.uid 
			left join mt_member_vip b on b.id=c.vid 
			where a.id=` + uid)[0]
		var mt int
		var commission = "0.00"
		var cmoney = "0.00"
		car := models.Query(`select a.price,a.spec,a.num,b.number,b.ispromote from mt_order_car a left join mt_product b on a.pid=b.id where a.id in(` + carid + `)`)
		for _, v := range car {
			ispromote := fmt.Sprint(v["ispromote"])
			spec := fmt.Sprint(v["spec"])
			price := fmt.Sprint(v["price"])
			num := fmt.Sprint(v["num"])
			number := fmt.Sprint(v["number"])
			if ispromote == "1" {
				if spec == "0" {
					cmoney = sword.Sum(cmoney, sword.Mult(sword.Mult(price, number), num))
				} else {
					cmoney = sword.Sum(cmoney, sword.Mult(price, num))
				}
			}
		}
		if ot == "0" && puid != "0" {
			ut := fmt.Sprint(mem["type"])
			if ut == "1" {
				distribution := fmt.Sprint(mem["distribution"])
				commission = sword.Divi(sword.Mult(cmoney, distribution), "100")
				mt = 4 //推广
			} else if ut == "2" {
				pfold, err := strconv.ParseFloat(fmt.Sprint(mem["fold"]), 64)
				if err != nil {
					mt = 0
				}
				ufold, err := strconv.ParseFloat(fmt.Sprint(umem["fold"]), 64)
				if err != nil {
					ufold = 100
				}
				if pfold > ufold {
					mt = 0
				} else {
					cut := (ufold - pfold) / 100
					mt = 2 //分销
					cuts := fmt.Sprintf(`%.2f`, cut)
					commission = sword.Mult(cuts, cmoney)
				}
			}
			if mt > 0 {
				money = sword.Cut(money, commission)
				if commission != "0.00" {
					commission = sword.Divi(sword.Mult(commission, sword.Cut("100", fmt.Sprint(system["handlingfee"]))), "100")
					if _, err := o.Raw(fmt.Sprintf(`insert into mt_member_money_detail (uid,type,money,addtime,oid) values ('%v','%v','%v','%v','%v')`,
						puid, mt, commission, nowtimes, id)).Exec(); err != nil {
						beego.Debug(err)
						o.Rollback()
						return err
					}
					if _, err := o.Raw(fmt.Sprintf(`update mt_member set money=money+%v where id=%v`, commission, puid)).Exec(); err != nil {
						beego.Debug(err)
						o.Rollback()
						return err
					}
				}
			}
		}

		var g orm.Params
		if gid != "0" {
			g = models.Query(`select a.uid,b.wx_openid_gzh as openid from mt_shop a left join mt_member b on a.uid=b.id where a.id=` + gid)[0]
			// if _, err := o.Raw(fmt.Sprintf(`insert into mt_member_money_detail (uid,type,money,oid,addtime) value ('%v',5,'%v','%v','%v')`,
			// 	g["uid"], money, id, nowtimes)).Exec(); err != nil {
			// 	beego.Debug(err)
			// 	o.Rollback()
			// 	return err
			// }
			if _, err := o.Raw(fmt.Sprintf(`update mt_member set money=money+%v where id=%v`, money, g["uid"])).Exec(); err != nil {
				beego.Debug(err)
				o.Rollback()
				return err
			}
			if _, err := o.Raw(`insert into mt_member_money_detail (uid,type,money,oid,addtime) values (?,5,?,?,?)`, g["uid"], money, id, nowtimes).Exec(); err != nil {
				beego.Debug(err)
				o.Rollback()
				return err
			}
		} else {
			g = models.Query(`select b.wx_openid_gzh as openid from mt_systems a left join mt_member b on a.uid=b.id`)[0]
		}
		o.Commit()
		var first string
		var purl string
		if mt == 4 {
			first = `您获得了一笔推广佣金`
			purl = "/mobile/my/promotion"
		} else if mt == 2 {
			first = `您获得了一笔分销收入`
			purl = "/mobile/my/distribution"
		}
		if mt > 0 {
			data := map[string]map[string]interface{}{
				"first":    {"value": first},
				"keyword1": {"value": order["ordernum"]},
				"keyword2": {"value": money},
				"keyword3": {"value": commission, "color": "#e4393c"},
				"keyword4": {"value": sword.Gettimes(""), "color": "#9c9c9c"},
				"remark":   {"value": models.Systems()["name"].(string) + `感谢有您`},
			}
			models.Push(fmt.Sprint(mem["wx_openid_gzh"]), `2vQpBTpzS5F1LelBqH2rSrjQLPhy6jp9vDtEu5yH0hk`, data, models.Urlc+purl, "")
		}
		gopenid := g["openid"]
		var pnames []string
		pname := models.Query(`select b.title from mt_order_car a left join mt_product b on a.pid=b.id where a.id in(` + carid + `)`)
		for _, v := range pname {
			pnames = append(pnames, fmt.Sprint(v["title"]))
		}
		data2 := map[string]map[string]interface{}{
			"first":    {"value": `买家已经确认收货`},
			"keyword1": {"value": order["ordernum"], "color": "#e4393c"},
			"keyword2": {"value": strings.Join(pnames, "、")},
			"keyword3": {"value": order["addtime"]},
			"keyword4": {"value": order["shippingtime"]},
			"keyword5": {"value": sword.Gettimes(""), "color": "#9c9c9c"},
			"remark":   {"value": `订单已被确认收货。`},
		}
		models.Push(fmt.Sprint(gopenid), `LZPCvc5XprPhXmoKQwMY4A-GaWoY6MwpyK1959-wHEo`, data2, models.Urlc+"/mobile/my/shop_order", "")

		data3 := map[string]map[string]interface{}{
			"first":    {"value": `确认收货成功`},
			"keyword1": {"value": order["ordernum"], "color": "#e4393c"},
			"keyword2": {"value": strings.Join(pnames, "、")},
			"keyword3": {"value": order["addtime"]},
			"keyword4": {"value": order["shippingtime"]},
			"keyword5": {"value": sword.Gettimes(""), "color": "#9c9c9c"},
			"remark":   {"value": `您可以给您的订单一个评价~`},
		}
		models.Push(fmt.Sprint(umem["wx_openid_gzh"]), `LZPCvc5XprPhXmoKQwMY4A-GaWoY6MwpyK1959-wHEo`, data3, models.Urlc+"/mobile/my/order", "")
	}
	return nil
}

func ProductClick(pid, uid string) {
	now := sword.Gettimes("")
	if err := models.Exec(`update mt_product set click=click+1 where id=` + pid); err != nil {
		beego.Debug(err)
	}
	if uid != "" {
		var p int
		if is := models.Query(`select id,addtime from mt_systems_reading where status=1 and uid=` + uid + ` and pid=` + pid); is != nil {
			addtime := is[0]["addtime"].(string)
			atime, _ := time.Parse(Tparse, addtime)
			ntime, _ := time.Parse(Tparse, now)
			jg := time.Second * 60
			if ntime.Sub(atime) > jg {
				p = 1
			}
			if err := models.Exec(`update mt_systems_reading set click=click+1,addtime='` + now + `' where id=` + is[0]["id"].(string)); err != nil {
				beego.Debug(err)
			}
		} else {
			if err := models.Exec(`insert into mt_systems_reading (status,uid,pid,click,addtime) values (1,` + uid + `,` + pid + `,1,'` + sword.Gettimes("") + `')`); err != nil {
				beego.Debug(err)
			}
			p = 1
		}
		product := models.Query(`select b.style,a.gid,a.title from mt_product a left join mt_shop b on a.gid=b.id where a.id=` + pid)[0]
		gid := fmt.Sprint(product["gid"])
		style := fmt.Sprint(product["style"])
		//推送
		if p == 1 {
			var openid string
			if gid == "0" || (style == "nil" || style == "0") {
				openid = fmt.Sprint(models.Query(`select b.wx_openid_gzh as openid from mt_systems a left join mt_member b on a.uid=b.id`)[0]["openid"])
				// openid = `ozAyh0hReTtr069DAFrxxdqwpCpk`
			} else {
				openid = fmt.Sprint(models.Query(`select b.wx_openid_gzh as openid from mt_shop a left join mt_member b on a.uid=b.id where a.id=` + gid)[0]["openid"])
			}
			mem := models.Query(`select mobile,monicker from mt_member where id=` + uid)[0]
			data3 := map[string]map[string]interface{}{
				"first":    {"value": fmt.Sprintf(`您的 %v 被查看了`, product["title"])},
				"keyword1": {"value": mem["monicker"], "color": `#36353A`},
				"keyword2": {"value": mem["mobile"], "color": `#e31939`},
				"keyword3": {"value": sword.Gettimes("2006-01-02 15:04"), "color": "#9c9c9c"},
				"remark":   {"value": `若对方有购买意向,您可以与客户联系`},
			}
			models.Push(openid, `ouMtxdT9QQ0ize7EXVgG_XQUuRai1O2-43_T5JsvC-0`, data3, models.Urlc+"/mobile/column/product_content?id="+pid, "")
		}
	}
}

func ProductPrice(pid, uid string) (price, gid, tid string) {
	product := models.Query(`
		select a.isvip,a.price,b.style,a.gid 
		from mt_product a 
		left join mt_shop b on a.gid=b.id 
		where a.id=?`, pid)[0]
	price = fmt.Sprint(product["price"])
	isvip := fmt.Sprint(product["isvip"])
	style := fmt.Sprint(product["style"])
	if style == "0" || product["style"] == nil {
		gid = "0"
	} else {
		gid = fmt.Sprint(product["gid"])
	}
	tid = "0"
	nows := sword.Gettimes("")
	if sales := models.Query(`
		select id,price 
		from mt_active_sales 
		where pid=? and status=1 and end=0 and starttime<? and endtime>?`, pid, nows, nows); sales != nil {
		price = fmt.Sprint(sales[0]["price"])
		tid = "2"
	}
	//会员价
	if isvip == "1" && uid != "" {
		mem := models.Query(`
					select b.fold 
					from mt_member_vip_order a 
					join (select * from mt_member_vip where gid=? and status=1) b on a.vid=b.id 
					where a.uid=?`, gid, uid)
		if mem != nil {
			if fold := fmt.Sprint(mem[0]["fold"]); fold != "" && fold != "<nil>" {
				price = sword.Divi(sword.Mult(price, fold), "100")
			}
		}
	}

	//团购

	// if gbuy := models.Query(`
	// 	select id,price
	// 	from mt_active_gbuy
	// 	where pid=? and end=0 and starttime<? and endtime>?`, pid, nows, nows); gbuy != nil {
	// 	price = fmt.Sprint(gbuy[0]["price"])
	// 	tid = "1"
	// }
	//促销

	return price, gid, tid
}
func ProductPriceA(pid, uid string) (price, gid, tid string) {
	product := models.Query(`
		select a.isvip,a.price,b.style,a.gid 
		from mt_product a 
		left join mt_shop b on a.gid=b.id 
		where a.id=?`, pid)[0]
	price = fmt.Sprint(product["price"])
	isvip := fmt.Sprint(product["isvip"])
	style := fmt.Sprint(product["style"])
	if style == "0" || product["style"] == nil {
		gid = "0"
	} else {
		gid = fmt.Sprint(product["gid"])
	}
	tid = "0"
	nows := sword.Gettimes("")
	//会员价
	if isvip == "1" && uid != "" {
		mem := models.Query(`
					select b.fold 
					from mt_member_vip_order a 
					join (select * from mt_member_vip where gid=? and status=1) b on a.vid=b.id 
					where a.uid=?`, gid, uid)
		if mem != nil {
			if fold := fmt.Sprint(mem[0]["fold"]); fold != "" && fold != "<nil>" {
				price = sword.Divi(sword.Mult(price, fold), "100")
			}
		}
	}

	// 团购

	if gbuy := models.Query(`
		select id,price
		from mt_active_gbuy
		where pid=? and end=0 and starttime<? and endtime>?`, pid, nows, nows); gbuy != nil {
		price = fmt.Sprint(gbuy[0]["price"])
		tid = fmt.Sprint(gbuy[0]["id"])
	}
	// 促销

	return price, gid, tid
}

func FixPrice(pid string) {
	product := models.Query(`
		select a.isvip,a.price,b.style,a.gid 
		from mt_product a 
		left join mt_shop b on a.gid=b.id 
		where a.id=?`, pid)[0]
	var gid string
	price := fmt.Sprint(product["price"])
	isvip := fmt.Sprint(product["isvip"])
	style := fmt.Sprint(product["style"])
	number, _ := strconv.ParseFloat(fmt.Sprint(product["number"]), 64)
	nows := sword.Gettimes("")
	var tid = "0"
	if style == "0" || product["style"] == nil {
		gid = "0"
	} else {
		gid = fmt.Sprint(product["gid"])
	}
	if sales := models.Query(`
		select id,price 
		from mt_active_sales 
		where pid=? and status=1 and end=0 and starttime<? and endtime>?`, pid, nows, nows); sales != nil {
		price = fmt.Sprint(sales[0]["price"])
		tid = "2"
	}
	ordercar := models.Query(`select id,uid,num,price,spec,status from mt_order_car where pid=? and status<=2 `, pid)
	for _, v := range ordercar {
		uid := fmt.Sprint(v["uid"])
		//会员价
		var price2 = price
		var oldprice = fmt.Sprint(v["price"])
		var num = fmt.Sprint(v["num"])
		var spec = fmt.Sprint(v["spec"])
		if isvip == "1" && uid != "" {
			mem := models.Query(`
					select b.fold 
					from mt_member_vip_order a 
					join (select * from mt_member_vip where gid=? and status=1) b on a.vid=b.id 
					where a.uid=?`, gid, uid)
			if mem != nil {
				if fold := fmt.Sprint(mem[0]["fold"]); fold != "" && fold != "<nil>" {
					price2 = sword.Divi(sword.Mult(price2, fold), "100")
				}
			}
		}
		if v["status"] == "1" {

			if err := models.Exec(`update mt_order_car set price=?,type=? where id=?`, price2, tid, v["id"]); err != nil {
				beego.Debug(err)
			}
		} else {
			order := models.Query(`select id from mt_order where status=1 and concat(',',carid,',') like '%,` + fmt.Sprint(v["id"]) + `,%'`)
			if order != nil {
				if err := models.Exec(`update mt_order_car set price=?,type=? where id=?`, price2, tid, v["id"]); err != nil {
					beego.Debug(err)
				}
				oldprices := sword.Mult(num, oldprice)
				nowprices := sword.Mult(num, price2)
				oldpricei, _ := strconv.ParseFloat(oldprices, 64)
				nowpricei, _ := strconv.ParseFloat(nowprices, 64)
				cutprice := nowpricei - oldpricei
				if spec == "0" {
					cutprice *= number
				}
				if cutprice > 0 {
					if err := models.Exec(`update mt_order set money=money+? where id=?`, cutprice, v["id"]); err != nil {
						beego.Debug(err)
					}
				} else {
					if err := models.Exec(`update mt_order set money=money-? where id=?`, math.Abs(cutprice), v["id"]); err != nil {
						beego.Debug(err)
					}
				}
			}

		}

	}
}
